package com.evan.review.ipc;

import android.content.Context;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 运行在独立进程中的Activity
 * 在AndroidManifest.xml中通过android:process=":remote"声明在独立进程中运行
 */
public class RemoteProcessActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_process);

        // 显示当前进程信息
        displayProcessInfo();
        
        // 返回按钮
        Button btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> {
            finish();
        });
        
        // 静态变量测试按钮
        Button btnTestStatic = findViewById(R.id.btn_test_static);
        btnTestStatic.setOnClickListener(v -> {
            // 修改静态变量
            ProcessDataHolder.count++;
            // 显示当前值
            updateStaticVariableInfo();
        });
        
        // 显示静态变量当前值
        updateStaticVariableInfo();
        
        // 处理从文件共享示例传来的请求
        if (getIntent().getBooleanExtra("from_file_sharing", false)) {
            // 显示文件共享相关功能
            findViewById(R.id.file_sharing_section).setVisibility(View.VISIBLE);
            
            // 设置文件共享操作按钮监听
            findViewById(R.id.btn_read_file).setOnClickListener(v -> {
                readSharedFiles();
            });
            
            findViewById(R.id.btn_write_file).setOnClickListener(v -> {
                writeToSharedFiles("来自远程进程的数据");
            });
            
            // 立即读取文件内容
            readSharedFiles();
        } else {
            // 隐藏文件共享相关功能
            findViewById(R.id.file_sharing_section).setVisibility(View.GONE);
        }
    }
    
    // 读取共享文件内容
    private void readSharedFiles() {
        // 读取内部存储文件
        try {
            TextView tvFileContent = findViewById(R.id.tv_file_content);
            StringBuilder content = new StringBuilder();
            content.append("内部存储文件内容：\n");
            
            try {
                FileInputStream fis = openFileInput("shared_data.txt");
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    content.append(line).append("\n");
                }
                br.close();
                isr.close();
                fis.close();
            } catch (Exception e) {
                content.append("读取内部存储文件失败: ").append(e.getMessage()).append("\n");
            }
            
            content.append("\n外部存储文件内容：\n");
            
            // 读取外部存储文件
            try {
                File file = new File(getExternalFilesDir(null), "ext_shared_data.txt");
                if (!file.exists()) {
                    content.append("外部存储文件不存在\n");
                } else {
                    FileInputStream fis = new FileInputStream(file);
                    InputStreamReader isr = new InputStreamReader(fis);
                    BufferedReader br = new BufferedReader(isr);
                    String line;
                    while ((line = br.readLine()) != null) {
                        content.append(line).append("\n");
                    }
                    br.close();
                    isr.close();
                    fis.close();
                }
            } catch (Exception e) {
                content.append("读取外部存储文件失败: ").append(e.getMessage()).append("\n");
            }
            
            tvFileContent.setText(content.toString());
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "读取共享文件失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 向共享文件写入内容
    private void writeToSharedFiles(String message) {
        try {
            // 添加时间戳和进程ID
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
            String pid = String.valueOf(android.os.Process.myPid());
            String content = timestamp + " [远程进程 PID:" + pid + "] " + message + "\n";
            
            // 写入内部存储
            try {
                FileOutputStream fos = openFileOutput("shared_data.txt", Context.MODE_APPEND);
                OutputStreamWriter osw = new OutputStreamWriter(fos);
                osw.write(content);
                osw.flush();
                osw.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            // 写入外部存储
            try {
                File file = new File(getExternalFilesDir(null), "ext_shared_data.txt");
                FileOutputStream fos = new FileOutputStream(file, true); // append模式
                OutputStreamWriter osw = new OutputStreamWriter(fos);
                osw.write(content);
                osw.flush();
                osw.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            Toast.makeText(this, "已写入共享文件", Toast.LENGTH_SHORT).show();
            // 刷新显示
            readSharedFiles();
            
        } catch (Exception e) {
            Toast.makeText(this, "写入共享文件失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    
    // 显示当前进程信息
    private void displayProcessInfo() {
        TextView tvProcessInfo = findViewById(R.id.tv_remote_process_info);
        
        int pid = Process.myPid();
        String processName = getProcessName(pid);
        
        StringBuilder info = new StringBuilder();
        info.append("远程进程信息：\n\n");
        info.append("进程ID (PID): ").append(pid).append("\n");
        info.append("进程名称: ").append(processName).append("\n");
        info.append("应用包名: ").append(getPackageName()).append("\n\n");
        info.append("这个Activity运行在独立的进程中，与主进程相互隔离。\n");
        info.append("在AndroidManifest中通过android:process=\":remote\"指定。\n\n");
        info.append("多进程的优缺点：\n");
        info.append("优点：独立的内存空间，不会影响主进程稳定性，适合重量级任务\n");
        info.append("缺点：\n- 增加系统资源消耗\n- 进程间数据不共享\n- 需要特殊的IPC机制通信");
        
        tvProcessInfo.setText(info.toString());
    }
    
    // 获取进程名称
    private String getProcessName(int pid) {
        android.app.ActivityManager am = (android.app.ActivityManager) getSystemService(ACTIVITY_SERVICE);
        if (am != null) {
            for (android.app.ActivityManager.RunningAppProcessInfo processInfo : am.getRunningAppProcesses()) {
                if (processInfo.pid == pid) {
                    return processInfo.processName;
                }
            }
        }
        return "未知进程";
    }
    
    // 更新静态变量信息显示
    private void updateStaticVariableInfo() {
        TextView tvStaticVariable = findViewById(R.id.tv_static_variable);
        tvStaticVariable.setText("当前进程中的静态变量值: " + ProcessDataHolder.count + "\n" +
                "你会发现在不同进程中修改静态变量互不影响，因为每个进程都有自己独立的内存空间。");
    }
    
    /**
     * 用于测试静态变量在多进程间的隔离性
     */
    public static class ProcessDataHolder {
        public static int count = 0;
    }
} 